import * as os from 'node:os'
import { logger, RouterDecorator } from "f2e-server3";

const Router = RouterDecorator
const beginTime = Date.now()

const _getCPUInfo = () => {
    const cpus = os.cpus();
    let user = 0, nice = 0, sys = 0, idle = 0, irq = 0, total = 0;

    for (let cpu in cpus) {
        const times = cpus[cpu].times;
        user += times.user;
        nice += times.nice;
        sys += times.sys;
        idle += times.idle;
        irq += times.irq;
    }

    total += user + nice + sys + idle + irq;

    return {
        user,
        sys,
        idle,
        total,
    }
}
let initial = _getCPUInfo()
let cpuPercent = 0

export const begin_cpu_percent = () => {
    const latest = _getCPUInfo();
    const idle = latest.idle - initial.idle
    const total = latest.total - initial.total
    // 计算CPU使用率
    cpuPercent = Math.ceil(100 * (1 - idle / total));
    initial = latest
    setTimeout(begin_cpu_percent, 1000)
}

export const server_info = async () => {
    const now = Date.now()
    const total = os.totalmem()
    const free = os.freemem()
    return {
        /** 服务器时间 */
        now,
        /** 服务器运行时间 */
        duration: now - beginTime,
        /** CPU信息 */
        cpuPercent,
        /** 内存信息 */
        memPercent: Math.ceil(100 * (total - free) / total),
    }
}

class App {
    @Router('/api/server/shutdown')
    shutdown () {
        setTimeout(() => {
            logger.debug('手动关闭服务器')
            process.exit(0)
        }, 100);
        return {
            status: 200,
            message: '服务器已关闭',
        }
    }
}

export const app = new App()

